package com.smedi.ismedi.inmail.core.port.adapter.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.smedi.ismedi.file.dto.request.SignatureRequest;
import com.smedi.ismedi.file.dto.response.FileInfoResponse;
import com.smedi.ismedi.file.feign.RemoteFileFeignApi;
import com.smedi.ismedi.inmail.core.domain.dto.AttachmentQuery;
import com.smedi.ismedi.inmail.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.inmail.core.port.adapter.service.FileRemoteApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.BasicError;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@AllArgsConstructor
@Service
public class FileRemoteApiImpl implements FileRemoteApi {
    private final RemoteFileFeignApi remoteFileFeignApi;

    private final AdapterConverter adapterConverter;

    @Override
    public FileInfoResponse getFileOne(AttachmentQuery attachmentQuery) {
        ResponseData<List<FileInfoResponse>> responseData = remoteFileFeignApi.getFileList(new ArrayList<>(Collections.singletonList(attachmentQuery.getSignKey())));
        if (!responseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        List<FileInfoResponse> files = responseData.getData();
        if(CollectionUtils.isEmpty(files)){
            return null;
        }
        if(CollectionUtils.isNotEmpty(files)){
            return files.get(0);
        }
        return null;
    }

    @Override
    public List<FileInfoResponse> getFileList(AttachmentQuery attachmentQuery) {
        ResponseData<List<FileInfoResponse>> responseData = remoteFileFeignApi.getFileList(attachmentQuery.getSignKeys());
        if (!responseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        return responseData.getData();
    }

    @Override
    public List<FileInfoResponse> getFileListByPost(AttachmentQuery attachmentQuery) {
        ResponseData<List<FileInfoResponse>> responseData = remoteFileFeignApi.getFileListByPost(attachmentQuery.getSignKeys());
        if (!responseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        return responseData.getData();
    }

    @Override
    public String uploadFile(File inputFile) throws IOException {
        // 文件转MultipartFile
        FileItem fileItem = new DiskFileItem("file", Files.probeContentType(inputFile.toPath()), false, inputFile.getName(), (int) inputFile.length(), inputFile.getParentFile());
        try (OutputStream outputStream = fileItem.getOutputStream()) {
            outputStream.write(Files.readAllBytes(Paths.get(inputFile.getAbsolutePath())));
        }
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

        // 上传文件
        ResponseData<FileInfoResponse> fileUpLoadResponseData = remoteFileFeignApi.fileUpLoad(multipartFile);
        if (!fileUpLoadResponseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, fileUpLoadResponseData.getApplication(), String.valueOf(fileUpLoadResponseData.getErrorMsg()));
        }

        return fileUpLoadResponseData.getData().getSignKey();
    }

    @Override
    public String convertToPdf(String inputFileKey) {
        // 将文件转换为pdf
        ResponseData<FileInfoResponse> convertFileToPdfWithFileKeyResponseData = remoteFileFeignApi.postConvertFileToPdfWithFileKey(inputFileKey);
        if (!convertFileToPdfWithFileKeyResponseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, convertFileToPdfWithFileKeyResponseData.getApplication(), String.valueOf(convertFileToPdfWithFileKeyResponseData.getErrorMsg()));
        }

        return convertFileToPdfWithFileKeyResponseData.getData().getSignKey();
    }

    @Override
    public String postSignatures(List<SignatureRequest> signatureRequests) {
        ResponseData<FileInfoResponse> fileInfoResponseResponseData = remoteFileFeignApi.postSignatures(signatureRequests);
        if (!fileInfoResponseResponseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, fileInfoResponseResponseData.getApplication(), String.valueOf(fileInfoResponseResponseData.getErrorMsg()));
        }

        return fileInfoResponseResponseData.getData().getSignKey();
    }
}
